﻿using BoriPeter.NutritionFileSource.Interfaces;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using Windows.Storage;

namespace BoriPeter.NutritionFileSource
{
    public class FileSource<TList, TItem> where TList : IXMLList<TItem>
    {
        public FileSource(string _fileName)
        {
            this.FileName = _fileName;
        }

        private string fileName;
        public string FileName
        {
            get { return fileName; }
            set { fileName = value; }
        }

        #region ReadAllFromFileAsync()
        public async Task<List<TItem>> ReadAllFromFileAsync()
        {
            List<TItem> returnList;

            try
            {
                StorageFolder storageFolder = KnownFolders.DocumentsLibrary;

                StorageFile storageFile =
                    await storageFolder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists);

                Type[] serializedTypes = { typeof(TList) };

                XmlSerializer serializer = new XmlSerializer(typeof(TList), serializedTypes);

                using (var file = await storageFile.OpenAsync(FileAccessMode.Read))
                using (Stream inStream = file.AsStreamForRead())
                {
                    returnList = ((TList)serializer.Deserialize(inStream)).GetItems();
                }
            }
            catch (Exception)
            {
                Debug.WriteLine("Error occured during reading the following file: {0}",fileName);
                returnList = new List<TItem>();
            }


            return returnList;
        }
        #endregion

        #region WriteAllToFileAsync()
        public async Task WriteAllToFileAsync(List<TItem> _list)
        {
            StorageFolder storageFolder = KnownFolders.DocumentsLibrary;

            Type[] serializedTypes = { typeof(TList) };

            XmlSerializer serializer = new XmlSerializer(typeof(TList), serializedTypes);

            var storageFile = await storageFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
            try
            {
                using (var file = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    Stream outStream = file.AsStreamForWrite();
                    TList list = (TList)Activator.CreateInstance<TList>();
                    list.SetItems(_list);
                    serializer.Serialize(outStream, list);
                }
            }
            catch (Exception)
            {
                Debug.WriteLine("Error occured during writing data into the following file: {0}", fileName);
            }
        }
        #endregion

    }
}
